package com.wyj.rpc.config;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * TODO: netty事件处理器
 *
 * @author wuyijie
 * @date 2021/12/26 2:25 下午
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable<Object> {
    ChannelHandlerContext channelHandlerContext;
    String requestMsg;
    String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.channelHandlerContext = ctx;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        responseMsg = msg;
        //唤醒等待线程
        notify();
    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public synchronized Object call() throws Exception {
        System.out.println("requestMsg="+requestMsg);
        //发送消息
        channelHandlerContext.writeAndFlush(requestMsg);
        //线程等待
        wait();
        return responseMsg;
    }
}
